package com.zxy.supplier_system.server.utils.wechat.official

import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
import com.zxy.supplier_system.server.utils.LoggerDelegate
import com.zxy.supplier_system.server.utils.Storage
import org.springframework.http.HttpRequest
import org.springframework.http.client.BufferingClientHttpRequestFactory
import org.springframework.http.client.ClientHttpRequestExecution
import org.springframework.http.client.ClientHttpRequestInterceptor
import org.springframework.http.client.ClientHttpResponse
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter
import org.springframework.util.StreamUtils
import org.springframework.web.client.RestTemplate
import java.nio.charset.StandardCharsets

data class WechatServerConfig(
    val token: String,
    val encodingAESKey: String
)

class WechatOfficialAccountHelper(
    val appId: String,
    val appSecret: String,
    val wechatServerConfig: WechatServerConfig?
) {
    internal val storage = Storage<String, String>()
    internal val restTemplate = RestTemplate().apply {
        this.requestFactory = BufferingClientHttpRequestFactory(this.requestFactory)
        this.interceptors.add(object: ClientHttpRequestInterceptor{
            override fun intercept(
                request: HttpRequest,
                body: ByteArray,
                execution: ClientHttpRequestExecution
            ): ClientHttpResponse {
                log.debug("Request body: {}", String(body, StandardCharsets.UTF_8));
                val response = execution.execute(request, body)
                val byteArray = StreamUtils.copyToByteArray(response.body)
                val bodyString = String(byteArray, StandardCharsets.UTF_8)
                log.debug("Response body: {}",bodyString)
                return response
            }
        })
        this.messageConverters = listOf(MappingJackson2HttpMessageConverter())
    }

    internal val objectMapper = ObjectMapper().apply {
        registerKotlinModule()
        this.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
    }

    internal val log by LoggerDelegate()
}

